// pages/countdown/countdown.js
var util = require('../../utils/util.js')
var http = require('../../utils/http.js')

// 在页面中定义激励视频广告
let videoAd = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    friendsHelp: false,
    fiveTimes: 5,
    moreCan: false,
    friendList: [],
    selfList: [
      {
        src: 'https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911164205.jpeg',
        name: '打开窗户看孤单透气',
        money: '砍掉7.88元'
      },
    ],
    swiperList: [
      {
      img: "https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911170490.jpeg",
    }, 
    {
        img: "https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911167600.jpeg",
    }, 
    {
        img: "https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911170326.jpeg",
    }, 
    {
        img: "https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911162735.jpeg",
    }, 
    {
        img: "https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911162735.jpeg",
    }, 
    {
        img: 'https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911164205.jpeg',
    }, 
    {
        img: "https://gxxc-1258879759.cos.ap-guangzhou.myqcloud.com/tree/utils/1543911164317.jpeg",
    }, 
  ],
  },
  time_receive: '',

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options);
    var index = options.index;
    var bargainId = options.id;
    that.setData({
      index,
      bargainId
    })
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-96e23d22adce41d3'
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {})
      videoAd.onClose((res) => {
        if (res && res.isEnded || res === undefined) {
          console.log("我看完视频了");
          that.selfCanReward();
        } else {
          // 播放中途退出，进行提示
          wx.showToast({
            title: '观看广告时间不足，无法获得奖励',
            icon: "none",
            duration: 2000
          })
        }
      })
    }
    //20
    const data = {
      bargainId: bargainId
    }
    http.myDiscount(data).then( res => {
      var userBargain = res.UserBargain;
      console.log('创建时间',JSON.stringify(userBargain.createTime));
      var createTime = (userBargain.createTime).split(' ');
      var createCurrent = createTime[1].split(':');
      //创建时的hours
      var createHours = parseFloat(createCurrent[0]);
      //创建时的minutes
      var createMinutes = parseFloat(createCurrent[1]);
      //创建时的seconds
      var createSeconds = parseFloat(createCurrent[2]);
      //创建时的总秒数
      var totalSeconds = createHours*60*60 + createMinutes*60 + createSeconds;
      //创建时的秒数加上12个小时，减去当前的秒数，就是倒计时的总秒数
      var endTime = totalSeconds + 12*60*60;
      //当前时间
      var now = new Date();
      var currentSeconds = (parseFloat(now.getHours()))*60*60 + (parseFloat(now.getMinutes()))*60 + parseFloat(now.getSeconds());
      //剩余时间
      var restSeconds = endTime - currentSeconds;
      that.receive_time(restSeconds);

      userBargain.haveMoney = Math.floor(userBargain.haveMoney / 10000 *100)/100;
      var toastMoney = userBargain.haveMoney;
      var restMoney = Math.floor((userBargain.money / 10000 - userBargain.haveMoney) * 100)/100;
      var friendList = res.helpBargains;
      for( var i = 0; i < friendList.length; i++) {
        friendList[i].realName = unescape(friendList[i].realName);
        if( friendList[i].money > 1000) {
          friendList[i].money = Math.floor((friendList[i].money / 10000) * 100 ) / 100
        } else {
          friendList[i].money = friendList[i].money / 10000;
        }
      }
      // console.log('1111111',userBargain);
      that.setData({
        userBargain,
        friendList,
        restMoney,
        toastMoney,
      })
      if( index == 0) {
        var newDay0 = new Date().toLocaleDateString();//获取当前日期
        var oldDay0 = wx.getStorageSync('oldDay0',oldDay0);
        if( oldDay0) {
          if( newDay0 != oldDay0) {
            that.setData({
              fiveTimes: 1,
            })
            setTimeout(() => {
              that.setData({
                fiveTimes: 5,
              })
            },1500)
            oldDay0 = newDay0;
            wx.setStorageSync('oldDay0',oldDay0);
          }
        } else {
          that.setData({
            fiveTimes: 1,
          })
          setTimeout(() => {
            that.setData({
              fiveTimes: 5,
            })
          },1500)
          oldDay0 = newDay0;
          wx.setStorageSync('oldDay0', oldDay0);
        }
      } else if( index == 1) {
        var newDay1 = new Date().toLocaleDateString();//获取当前日期
        var oldDay1 = wx.getStorageSync('oldDay1',oldDay1);
        if( oldDay1) {
          if( newDay0 != oldDay1) {
            that.setData({
              fiveTimes: 1,
            })
            setTimeout(() => {
              that.setData({
                fiveTimes: 5,
              })
            },1500)
            oldDay1 = newDay1;
            wx.setStorageSync('oldDay1',oldDay1);
          }
        } else {
          that.setData({
            fiveTimes: 1,
          })
          setTimeout(() => {
            that.setData({
              fiveTimes: 5,
            })
          },1500)
          oldDay1 = newDay1;
          wx.setStorageSync('oldDay1', oldDay1);
        }
      } else if( index == 2) {
        var newDay2 = new Date().toLocaleDateString();//获取当前日期
        var oldDay2 = wx.getStorageSync('oldDay2',oldDay2);
        if( oldDay2) {
          if( newDay2 != oldDay2) {
            that.setData({
              fiveTimes: 1,
            })
            setTimeout(() => {
              that.setData({
                fiveTimes: 5,
              })
            },1500)
            oldDay2 = newDay2;
            wx.setStorageSync('oldDay2',oldDay2);
          }
        } else {
          that.setData({
            fiveTimes: 1,
          })
          setTimeout(() => {
            that.setData({
              fiveTimes: 5,
            })
          },1500)
          oldDay2 = newDay2;
          wx.setStorageSync('oldDay2', oldDay2);
        }
      } else {
        var newDay3 = new Date().toLocaleDateString();//获取当前日期
        var oldDay3 = wx.getStorageSync('oldDay3',oldDay3);
        if( oldDay3) {
          if( newDay3 != oldDay3) {
            that.setData({
              fiveTimes: 1,
            })
            setTimeout(() => {
              that.setData({
                fiveTimes: 5,
              })
            },1500)
            oldDay3 = newDay3;
            wx.setStorageSync('oldDay3',oldDay3);
          }
        } else {
          that.setData({
            fiveTimes: 1,
          })
          setTimeout(() => {
            that.setData({
              fiveTimes: 5,
            })
          },1500)
          oldDay3 = newDay3;
          wx.setStorageSync('oldDay3', oldDay3);
        }
      }
    })
  },
  // 12小时倒计时
	receive_time: function(time) {
    var that = this;
		clearInterval(that.time_receive);
		var hour = 0;
		var point = 0;
		var second = 0;
		var time_receive = setInterval(function() {
			time--;
			hour = parseInt(time / 3600);
			point = parseInt(time % 3600);
			point = parseInt(point / 60);
			second = parseInt(time % 60)
			if (hour < 10) {
				hour = "0" + hour
			}
			if (point < 10) {
				point = "0" + point
			}
			if (second < 10) {
				second = "0" + second
			}
			if (time <= 0) {
				clearInterval(time_receive);
			}
			that.setData({
				hour: hour,
				point: point,
				second: second
			})
    }, 1000)
    that.time_receive = time_receive;
  },
  // 自己砍自己接口
  selfCanReward:function() {
    var that = this;
    const data = {
      bargainId: that.data.bargainId
    }
    //21 看视频砍价
    http.videoBargain(data).then( res => {
      var friendList = that.data.friendList;
      console.log('未砍自己之前的助力榜数组',friendList)
      var videoBargain = res.helpBargain;
      videoBargain.money = videoBargain.money / 10000;
      var toastMoney = videoBargain.money;
      friendList = [...friendList,...videoBargain];
      console.log('我是自己砍过自己的助力榜数组',friendList);
      that.setData({
        friendList,
        moreCan: true,
        fiveTimes: 1,
        toastMoney
      })
    }, err => {
      wx.showModal({
        title: '提示',
        content: err,
      })
    })
    setTimeout(() => {
      that.setData({
        fiveTimes: 5,
      })
    },1500)
  },
  // 自己砍自己：
  moreCan: function() {
    var that = this;
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }

  },
  // 邀请好友砍价
  invite: function() {
    var that = this;
    var bargainId = that.data.bargainId;
    var userId = wx.getStorageSync("userId");
    // wx.navigateTo({
    //   url: "/pages/friends/friends?userId=" +userId+"&bargainId=" +bargainId,
    // })
  },
  onShareAppMessage: function() {
    var that = this;
    var bargainId = that.data.bargainId;
    var userId = wx.getStorageSync("userId");
    return {
      title: '好友邀请你砍一刀，免费领取100块钱红包？',
      path: "/pages/friends/friends?userId=" +userId+"&bargainId=" +bargainId,
    }
  },
  back:function () {
    wx.navigateBack({
      delta: 1
    })
  },
  // 关闭领取砍价弹窗
  closeFive: function() {
    var that = this;
    that.setData({
      fiveTimes: 5,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var that = this;
    setTimeout(() => {
      that.setData({
        friendsHelp: true,
      })
    },3000)
  },
  // 好友助力弹窗关闭
  friendsClo: function() {
    this.setData({
      friendsHelp: false,
    })
  },
//领取砍价money
getCanMoney: function() {
  var that = this;
  var bargainId = that.data.bargainId;
  const data = {
    bargainId: bargainId
  }
  http.bargainReward(data).then( res => {
    var getCanMoney = res.money / 10000;
    that.setData({
      getCanMoney,
      fiveTime: 2
    })
  })
},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
		clearInterval(that.time_receive);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
		clearInterval(that.time_receive);

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})